package top.codedance.iotp.client.manage.net.handler;

import cd.io.netty.channel.ChannelHandlerContext;
import cd.io.netty.channel.SimpleChannelInboundHandler;
import top.codedance.iotp.client.manage.ManageApplication;
import top.codedance.iotp.client.manage.net.listenner.TaskExecuter;
import top.codedance.iotp.common.entity.CommandTeam;
import top.codedance.iotp.common.entity.CommonEntity;

import java.util.Map;
import java.util.Set;
import java.util.UUID;

public class TaskChannelHandler extends SimpleChannelInboundHandler<CommonEntity> {

    protected void messageReceived(final ChannelHandlerContext channelHandlerContext, final CommonEntity commonEntity) throws Exception {
        Set<Map.Entry<CommandTeam, TaskExecuter>> entries = ManageApplication.excuters.entrySet();
        for (Map.Entry<CommandTeam, TaskExecuter> entry : entries) {
            CommandTeam commandTeam = entry.getKey();
            if (commonEntity.getCommand() == commandTeam.getResponseCommand()) {
                final TaskExecuter taskExecuter = entry.getValue();
                ManageApplication.workerPool.submit(() -> {
                    taskExecuter.exec(channelHandlerContext, commonEntity.getBody(), UUID.randomUUID().toString());
                });
                break;
            }
        }
        channelHandlerContext.fireChannelRead(commonEntity); //向后传递
    }
}
